﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OpenSource.SpreadsheetFactory.Internal.Html
{
    internal class HtmlGenerator<T> : SpreadsheetGenerator<T>
    {
        public HtmlGenerator(IEnumerable<T> source)
            : base(source)
        {
        }

        internal override byte[] GenerateSpreadsheet()
        {
            StringBuilder sb = new StringBuilder();
            GenerateHtmlHeader(sb);
            GenerateHtmlBody(sb);
            GenerateHtmlFooter(sb);

            return Encoding.UTF8.GetBytes(sb.ToString());
        }

        private void GenerateHtmlHeader(StringBuilder sb)
        {
            sb.AppendLine(@"<?xml version=""1.0"" encoding=""UTF-8""?>");
            sb.AppendLine
                (
                    @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" "+
                    @"""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"""
                );
            sb.AppendLine(@"<html xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en"">");
            sb.AppendLine(" <head>");
            sb.Append("  <title>");
            sb.Append(System.Web.HttpUtility.HtmlEncode(Title));
            sb.AppendLine("</title>");
            sb.AppendLine(" </head>");
        }

        private static void GenerateHtmlFooter(StringBuilder sb)
        {
            sb.Append("</html>");
        }

        private void GenerateHtmlBody(StringBuilder sb)
        {
            sb.AppendLine(" <body>");
            sb.AppendLine("  <table>");
            GenerateTableHeader(sb);
            GenerateTableBody(sb);
            sb.AppendLine("  </table>");
            sb.AppendLine(" </body>");
        }

        private void GenerateTableHeader(StringBuilder sb)
        {
            sb.AppendLine("   <thead>");
            sb.AppendLine("    <tr>");

            foreach (Column<T> column in Columns)
            {
                sb.Append("     <th>");
                sb.Append(System.Web.HttpUtility.HtmlEncode(column.Title));
                sb.AppendLine("</th>");
            }

            sb.AppendLine("    </tr>");
            sb.AppendLine("   </thead>");
        }

        private void GenerateTableBody(StringBuilder sb)
        {
            sb.AppendLine("   <tbody>");

            foreach (T item in Source)
            {
                sb.AppendLine("    <tr>");

                foreach (Column<T> column in Columns)
                {
                    sb.Append("     <td>");
                    sb.Append(System.Web.HttpUtility.HtmlEncode(column.GetColumnValue(item).ToString()));
                    sb.AppendLine("</td>");
                }

                sb.AppendLine("    </tr>");
            }

            sb.AppendLine("   </tbody>");
        }
    }
}
